
// 模块函数  -放与nav导航栏相关的所有函数
var initCourseTab = (function (doc) {
    var oNavItemlk = doc.getElementsByClassName('nav-item-lk'),
        data = JSON.parse(doc.getElementById('J-courseData').innerHTML),
        oTpl = doc.getElementById('J-courseItemTpl').innerHTML,
        oCourseList = doc.getElementsByClassName('J-course-list')[0],

        oNavItemlkLen = oNavItemlk.length;


    return {

        // nav绑定点击事件的回调函数
        navclick: function (e) {
            var e = e || window.event,
                tar = e.target || e.srcEvent,
                className = tar.className,
                item;

            if (className === 'nav-item-lk') {
                var field = tar.getAttribute('date-type');

                for (var i = 0; i < oNavItemlkLen; i++) {
                    item = oNavItemlk[i];
                    item.className = 'nav-item-lk';
                }
                tar.className += ' current';
                oCourseList.innerHTML = this.makeList(this.filterData(data, field));
            }
        },

        // 筛选数据
        filterData: function (data, val) {
            return data.filter(function (elem) {

                switch (val) {
                    case "all":
                        return true;
                        break;
                    case "vip":
                        return (elem.is_free == 0);
                        break;
                    case "free":
                        return (elem.is_free == 1);
                        break;
                    default:
                        return true;
                }
            });

        },

        // 替换模板中的{{}}为JSON数据
        makeList: function (data) {
            var list = '';

            data.forEach(function (elem) {
                list += oTpl.replace(/{{(.*?)}}/g, function (node, key) {
                    return {
                        img: elem.img,
                        classes: elem.classes,
                        course: elem.course,
                        price: elem.price,
                        teacher: elem.teacher
                    }[key];
                });
            });

            return list;
        }

    };

})(document);


// 主函数
; (function (doc) {
    var oNavList = doc.getElementsByClassName('J-nav-list')[0];

    function init() {
        bindEvent();
    }

    function bindEvent() {
        oNavList.addEventListener('click', initCourseTab.navclick.bind(initCourseTab), false);
    }

    init();

})(document);